import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import { format } from "date-fns";
// 导入 API 服务层和工具函数
import { 
  patientCircleService,
  handleApiResponse,
  handleApiError
} from "../../utils/api";
// 导入类型定义
import type { 
  PatientCircleState,
  PatientCircleFormData,
  PatientCirclePublishResponse,
  KnowledgeBaseItem,
  DiseaseListItem,
  PatientCircleDetailResponse,
  PatientCircleCommentItem,
  PatientCircleDetailParams,
  PatientCircleCommentParams,
  PublishCommentParams,
  ImageUploadParams,
  SickCollectionParams,
  CommentListParams,
  ExpressOpinionParams
} from "../../type/store";

// ==================== 异步 Action Creator 定义 ====================

// 获取科室分类列表
export const getKnowledgeBase = createAsyncThunk(
  "patientCircle/getKnowledgeBase",
  async (): Promise<KnowledgeBaseItem[]> => {
    try {
      const response = await patientCircleService.getKnowledgeBase();
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(
        handleApiError(error) || "获取科室分类失败"
      );
    }
  }
);

// 根据科室ID获取病症列表
export const getKnowledgeBaseListByID = createAsyncThunk(
  "patientCircle/getKnowledgeBaseListByID",
  async (departmentId: number): Promise<DiseaseListItem[]> => {
    try {
      const response = await patientCircleService.getKnowledgeBaseListByID(departmentId);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(
        handleApiError(error) || "获取病症列表失败"
      );
    }
  }
);

// 发布病友圈帖子
export const publishSickCircle = createAsyncThunk(
  "patientCircle/publishSickCircle",
  async (data: PatientCircleFormData): Promise<PatientCirclePublishResponse> => {
    try {
      const response = await patientCircleService.publishSickCircle(data);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(
        handleApiError(error) || "发布病友圈失败"
      );
    }
  }
);

// 上传病友圈图片
export const uploadSickCirclePicture = createAsyncThunk(
  "patientCircle/uploadSickCirclePicture",
  async (params: ImageUploadParams): Promise<any> => {
    try {
      const response = await patientCircleService.uploadSickCirclePicture(params.sickCircleId, params.picture);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(
        handleApiError(error) || "上传图片失败"
      );
    }
  }
);

// 获取病友圈详情
export const getSickCircleDetail = createAsyncThunk(
  "patientCircle/getSickCircleDetail",
  async (params: PatientCircleDetailParams): Promise<PatientCircleDetailResponse> => {
    try {
      const response = await patientCircleService.getSickCircleDetail(params);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(
        handleApiError(error) || "获取病友圈详情失败"
      );
    }
  }
);

// 获取病友圈评论列表
export const getSickCircleCommentList = createAsyncThunk(
  "patientCircle/getSickCircleCommentList",
  async (params: PatientCircleCommentParams): Promise<PatientCircleCommentItem[]> => {
    try {
      const response = await patientCircleService.getSickCircleCommentList(params);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(
        handleApiError(error) || "获取评论列表失败"
      );
    }
  }
);

// 发表评论
export const publishComment = createAsyncThunk(
  "patientCircle/publishComment",
  async (data: PublishCommentParams): Promise<any> => {
    try {
      const response = await patientCircleService.publishComment(data);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(
        handleApiError(error) || "发表评论失败"
      );
    }
  }
);

// 收藏病友圈
export const postCollection = createAsyncThunk(
  "patientCircle/postCollection",
  async (data: SickCollectionParams): Promise<any> => {
    try {
      const response = await patientCircleService.postCollection(data);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(
        handleApiError(error) || "收藏失败"
      );
    }
  }
);

// 取消收藏病友圈
export const deleteCollection = createAsyncThunk(
  "patientCircle/deleteCollection",
  async (params: SickCollectionParams): Promise<any> => {
    try {
      const response = await patientCircleService.deleteCollection(params);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(
        handleApiError(error) || "取消收藏失败"
      );
    }
  }
);

// 查询病友圈评论列表（新接口）
export const getCircleComment = createAsyncThunk(
  "patientCircle/getCircleComment",
  async (params: CommentListParams): Promise<PatientCircleCommentItem[]> => {
    try {
      const response = await patientCircleService.getCircleComment(params);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(
        handleApiError(error) || "获取评论列表失败"
      );
    }
  }
);

// 赞同/反对病友圈评论
export const putExpressOpinion = createAsyncThunk(
  "patientCircle/putExpressOpinion",
  async (params: ExpressOpinionParams): Promise<any> => {
    try {
      const response = await patientCircleService.putExpressOpinion(params);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(
        handleApiError(error) || "操作失败"
      );
    }
  }
);

// ==================== Redux Slice 定义 ====================

const PatientCircleSlice = createSlice({
  name: "patientCircle",
  initialState: {
    status: "idle" as const,
    error: "",
    
    // 科室分类数据
    knowledgeBaseList: [] as KnowledgeBaseItem[],
    
    // 病症列表数据
    diseaseList: [] as DiseaseListItem[],
    
    // 病友圈详情数据
    sickCircleDetail: {
      sickCircleId: 0,
      authorUserId: 0,
      departmentId: 0,
      adoptFlag: 0,
      title: "",
      department: "",
      disease: "",
      detail: "",
      treatmentHospital: "",
      treatmentStartTime: "",
      treatmentEndTime: "",
      treatmentProcess: "",
      picture: "",
      collectionFlag: 0,
      collectionNum: "0",
      commentNum: 0,
      adoptNickName: "",
      adoptHeadPic: "",
      adoptComment: "",
      adoptTime: 0
    } as PatientCircleDetailResponse,
    
    // 评论列表数据
    commentList: [] as PatientCircleCommentItem[],
    
    // 发布状态
    publishResult: null as PatientCirclePublishResponse | null,
    
    // 上传状态
    uploadStatus: "idle" as const,
    uploadError: "",
    
  } as PatientCircleState,
  
  // 同步 Reducer 函数
  reducers: {
    // 清空病症列表
    clearDiseaseList(state) {
      state.diseaseList = [];
    },
    
    // 清空评论列表
    clearCommentList(state) {
      state.commentList = [];
    },
    
    // 清空发布结果
    clearPublishResult(state) {
      state.publishResult = null;
    },
    
    // 清空错误信息
    clearError(state) {
      state.error = "";
      state.uploadError = "";
    },
    
    // 重置状态
    resetStatus(state) {
      state.status = "idle";
      state.uploadStatus = "idle";
    }
  },
  
  // 异步处理 - 先使用 addCase，再使用 addMatcher
  extraReducers: (builder) => {
    // 专门处理图片上传的状态 - 必须在 addMatcher 之前
    builder
      .addCase(uploadSickCirclePicture.pending, (state) => {
        state.uploadStatus = "loading";
        state.uploadError = "";
      })
      .addCase(uploadSickCirclePicture.fulfilled, (state) => {
        state.uploadStatus = "succeeded";
      })
      .addCase(uploadSickCirclePicture.rejected, (state, action) => {
        state.uploadStatus = "failed";
        state.uploadError = action.error.message || "上传失败";
      });
    
    // 通用的成功状态处理 - 匹配所有以 '/fulfilled' 结尾的 action
    builder.addMatcher(
      (action) => action.type.endsWith('/fulfilled'),
      (state, action: any) => {
        // 统一设置成功状态
        state.status = "succeeded";
        
        // 根据不同的 action 类型，更新对应的状态数据
        switch (action.type) {
          // 科室分类列表获取成功
          case getKnowledgeBase.fulfilled.type:
            state.knowledgeBaseList = action.payload;
            break;
          
          // 病症列表获取成功
          case getKnowledgeBaseListByID.fulfilled.type:
            state.diseaseList = action.payload;
            break;
          
          // 病友圈详情获取成功
          case getSickCircleDetail.fulfilled.type:
            state.sickCircleDetail = action.payload;
            break;
          
          // 评论列表获取成功
          case getSickCircleCommentList.fulfilled.type:
            state.commentList = action.payload;
            break;
          
          // 发布病友圈成功
          case publishSickCircle.fulfilled.type:
            state.publishResult = action.payload;
            break;
          
          // 发表评论成功
          case publishComment.fulfilled.type:
            // 发表评论成功后，可以重新获取评论列表
            break;
          
          // 收藏病友圈成功
          case postCollection.fulfilled.type:
            // 收藏成功后，可以更新病友圈详情中的收藏状态
            break;
          
          // 取消收藏病友圈成功
          case deleteCollection.fulfilled.type:
            // 取消收藏成功后，可以更新病友圈详情中的收藏状态
            break;
          
          // 查询病友圈评论列表成功（新接口）
          case getCircleComment.fulfilled.type:
            state.commentList = action.payload;
            break;
          
          // 赞同/反对病友圈评论成功
          case putExpressOpinion.fulfilled.type:
            // 操作成功后，可以重新获取评论列表
            break;
        }
      }
    );
    
    // 通用的失败状态处理 - 匹配所有以 '/rejected' 结尾的 action
    builder.addMatcher(
      (action) => action.type.endsWith('/rejected'),
      (state, action: any) => {
        state.status = "failed";
        state.error = action.error.message || "操作失败";
      }
    );
    
    // 通用的加载状态处理 - 匹配所有以 '/pending' 结尾的 action
    builder.addMatcher(
      (action) => action.type.endsWith('/pending'),
      (state) => {
        state.status = "loading";
        state.error = "";
      }
    );
  },
});

export const { 
  clearDiseaseList, 
  clearCommentList, 
  clearPublishResult, 
  clearError, 
  resetStatus 
} = PatientCircleSlice.actions;

export default PatientCircleSlice.reducer;
